import type { ConfigStorage } from './config-storage';
import { getStorageSync, setStorage } from '../../utils/storage.ts'
export interface GiteeRepoConfig {
  owner: string;
  repo: string;
  filePath: string;
}
export interface GiteeTokenResponse {
  access_token: string;
  token_type: string;
  expires_in: number;
  refresh_token: string;
  scope: string;
  created_at: number;
}
const rawUrl = (owner: string, repo: string, path: string, token: string) => `https://gitee.com/api/v5/repos/${owner}/${repo}/raw/${path}?access_token=${token}`;
const editUrl = (owner: string, repo: string, path: string) => `https://gitee.com/${owner}/${repo}/blob/${path}`;

export class GiteeConfigStorage implements ConfigStorage {
  private token: string | null = null;
  constructor(private config: GiteeRepoConfig) { }
  async getToken(): Promise<string | null> {
    getStorageSync('git_token',).then((result: GiteeTokenResponse) => {
      if (result && result.access_token) {
        this.token = result.access_token;
      }
    });
    const body = new URLSearchParams({
      grant_type: 'password',
      username: "lsl200817@163.com",
      password: "lsl52640.",
      client_id: "87214585eefed55409521aa1f7bdfa10fca931ffedd2234abeb77ba530c2abf0",
      client_secret: "375ea53f39ed31d11e53dea416ff81c2b319fe4927ffc15a06341bf78fe6fcb5",
      scope: "projects",
    });

    const response = await fetch('https://gitee.com/oauth/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body,
    });

    if (!response.ok) {
      const text = await response.text();
      throw new Error(`请求失败: ${response.status} ${text}`);
    }

    const data = (await response.json()) as GiteeTokenResponse;
    this.token = data["access_token"];
    if (data) {
      setStorage("git_token", data);
    }
    return data["access_token"];
  }
  async load(): Promise<string> {
    if (!this.token) {
      await this.getToken();
    };
    if (!this.token) {
      throw new Error('Token is not available.');
    }
    const { repo, owner, filePath } = this.config;
    const res = await fetch(rawUrl(owner, repo, filePath, this.token), {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    });
    if (!res.ok) return "";
    const data = await res.json();
    const content = atob(data.content);
    return JSON.parse(content);
  }

  async save(content: string): Promise<void> {
    if (!this.token) {
      await this.getToken();
    };
    if (!this.token) {
      throw new Error('Token is not available.');
    }
    const { repo, owner, filePath } = this.config;
    const url = editUrl(repo, owner, filePath);
    fetch(rawUrl(repo, owner, filePath, this.token), {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    }).then((res: any) => {
      if (res.status === 404) {
        // 新增
        fetch(url, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            access_token: this.token,
            message: "update config",
            content: btoa(content),
          }),
        });

      } else {
        // 更新
        fetch(url, {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            access_token: this.token,
            sha: res.data.sha,
            message: "update config",
            content: btoa(content),
          }),
        });
      }
    });
  }
}
